﻿var innerhtml = "";
var curentresizeitem;
var relateresizeitem;
var curleft = 0;
var rightpost = 0;
var tdheight = 0;
var tdwidth = 0;
var colitems;
var resizecolindex;
var tableincharge;
$.fn.InitialZoom = function () {
    if ($($(this).find(".maximize,.minimize")).length == 0) {
        $(this).prepend("<a class='minimize' style='display:none;' href='javascript:void(0);'>&nbsp;</a>");
        $(this).prepend("<a class='maximize' href='javascript:void(0);'>&nbsp;</a>");

        var parent = this;
        $(".maximize").click(function () {
            $("html").css("overflow", "hidden");
            var maxw = $(window).width();
            var maxh = $(window).height();
            $('body').addClass("in-maximize");
            var container = $(this).parent();
            $(container).addClass("in-maximize");
            $(container).css('min-width', maxw);
            $(container).css("overflow", "hidden");
            $(container).css("overflow-y", "hidden");
            $(container).css("overflow-x", "hidden");
            $(this).hide();
            $(".minimize").show();

            var autofit = $(container).find('*[autofit="true"]');
            if ($(autofit).length == 0)
                return;
            $(autofit).css('width', maxw);
            var autofheight = $(autofit).height();
            var autofittop = $(autofit).position().top;
            $(autofit).height(maxh - autofittop);
            var childrenresizeable = $(parent).find('table[resizeable="true"]');
            $.each(childrenresizeable, function (i, item) {
                $(childrenresizeable).css("width", "99%");
                FixResizeableTableHeader(item);
                AddFakeHeaderTable(item, i);
            });

            $(autofit).scroll(function () {
                var fitpos = $(this).scrollLeft();
                $($(container).find(".fake-header")).css("left", -fitpos + "px");
            });
        });

        $(".minimize").click(function () {
            $("html").css("overflow", "auto");
            $('body').removeClass("in-maximize");
            var container = $(this).parent();
            $(container).removeClass("in-maximize");
            $(container).height('auto');
            $(container).width('auto');
            $(container).css('min-width', "");
            $(this).hide();
            $(".maximize").show();
            var autofit = $(container).find('*[autofit="true"]');
            if ($(autofit).length == 0)
                return;
            $(autofit).css("height", "auto");
            $(autofit).css('width', $(container).width());
            var childrenresizeable = $(parent).find('table[resizeable="true"]');
            $("td.fake-td").remove();
            $.each(childrenresizeable, function (i, item) {
                RemoveFakeHeaderTable(i);
                FixResizeableTableHeader(item);

            });
        });
    }
    $.each($(this).find('table[resizeable="true"]'), function (i, item) {
        FixResizeableTableHeader(item);
    });

    $.each($(this).find(".resizeable"), function (i, item) {
        innerhtml = $(item).html();
        rightpost = $(item).position();
        tdwidth = $(item).width();
        tdheight = $(item).height();
        var lineheight = "";
        if (typeof $(item).attr("rowspan") != "undefined" && parseInt($(item).attr("rowspan")) > 1) {
            lineheight = "line-height:" + tdheight + "px;";
        }
        innerhtml = "<div style='float:left;width:89.25%;px;" + lineheight + "'>" + innerhtml + "</div>";
        var resizeitem = "<div class='item-resize' style='height:" + tdheight + "px;width:7px;float:right;cursor:col-resize;margin-right:-6px;'></div><div style='clear:both'></div>";
        $(item).html(innerhtml + resizeitem);
    });
    $(".item-resize").InitResize();
}
function FixResizeableTableHeader(item) {
    var maxtdcnt = 0;
    var _rstemp = 0;
    var fake = $(item).find("tr.fake-tr");
    if ($(fake).length > 0) {
        $(fake).remove();
    }
    var rowfound;
    $.each($(item).find("tr"), function (j, tr) {
        var t = $(tr).children("th").length > 0 ? $(tr).children("th").length : $(tr).children("td").length;
        if (t > maxtdcnt) {
            maxtdcnt = t;
            rowfound = tr;
        }
        if (j > 5)
            return;
    });
    var j = 0;
    var ftr = "<tr class='fake-tr'>";
    for (j = 0; j < maxtdcnt; j++) {
        var padding = 0;
        var border = 0;

        if ($($(rowfound).children()[j]).css("padding-left") != "") {
            padding += parseInt($($(rowfound).children()[j]).css("padding-left").replace("px", ""));
        }
        if ($($(rowfound).children()[j]).css("padding-right") != "") {
            padding += parseInt($($(rowfound).children()[j]).css("padding-right").replace("px", ""));
        }

        if ($($(rowfound).children()[j]).css("border-left-width") != "") {
            border += parseInt($($(rowfound).children()[j]).css("border-left-width").replace("px", ""));
        }
        if ($($(rowfound).children()[j]).css("border-right-width") != "") {
            border += parseInt($($(rowfound).children()[j]).css("border-right-width").replace("px", ""));
        }
        var _code = $($(rowfound).children()[j]).attr("code");
        if (typeof _code == "undefined")
            _code = "";
        ftr += "<td style='' code='" + _code + "'><div style='width:" + ($($(rowfound).children()[j]).width() - border - padding) + "px'></div></td>";
    }
    ftr += "</tr>"
    if ($(item).find("tr").length > 0) {
        $($(item).find("tr")[0]).before(ftr);
    }
}
function RemoveFakeHeaderTable(index) {
    $("#fakehead" + index).hide();
    $("#fakehead" + index).remove();
}

function AddFakeHeaderTable(item, index) {
    $("#fakehead" + index).remove();
    var header = $(item).children("thead").clone(true);
    var itemclass = $(item).attr("class");
    if (typeof itemclass == "undefined")
        itemclass = "";
    if ($(header).length == 0)
        header = $(item).find("tr")[0];

    if ($(header).length == 0) {
        return;
    }
    var borderleft = $(item).css("border-left-width").replace("px", "");
    var bordertop = $(item).css("border-top-width").replace("px", "");
    var hl = $(item).children("thead").position().left; //  - parseInt(borderleft);
    var ht = $(item).children("thead").position().top; //  - parseInt(bordertop);
    if ($.browser.mozilla) {
        hl = hl;
        ht = ht - parseInt(bordertop);
    } else {
        hl = hl + parseInt(borderleft);
    }

    var fakehead = "<div class='fake-header' id='fakehead" + index + "' style='position:fixed; top:" + ht + "px;left:" + hl + "px;width:" + $(item).width() + "px;'><table class='" + itemclass + "'></table></div>";
    $(item).after(fakehead);
    $('#fakehead' + index).children("table").append(header);
    $.each($(item).children("thead").find("td,th"), function (i, rtd) {
        var _rftd = $("#fakehead" + index).find("td,th")[i];
        if ($(rtd).hasClass("resizeable")) {
            $(rtd).children(".item-resize").attr("colindex", index + "_" + i);
            $(_rftd).children(".item-resize").attr("tableindex", index);
        }
    });
    $(item).attr("headid", "fakehead" + index);

    $.each($(item).find("tr.fake-tr td,tr.fake-tr th"), function (i, item) {
        var _w = $(item).width();
        $(item).children().width(_w);
        $($('#fakehead' + index).find("tr.fake-tr td,tr.fake-tr th")[i]).children().width(_w);
    });

    $($('#fakehead' + index).find("tr")).last().append("<td class='fake-td' style='position: fixed; right: -1000px; margin:0; padding:0; width:0px; '>&nbsp;</td>");
    $($('#fakehead' + index).find("tr.fake-tr")).append("<td class='fake-td' style=''><div style='width:1px'></div></td>");

    $.each($(item).find("tr"), function (i, tr) {
        $(tr).append("<td class='fake-td' style='position: fixed; right: -1000px; margin:0; padding:0; width:1px; '>&nbsp;</td>");
    });
}

function HideColumn(index, show) {
    var coltarget;
    if ($($(tableincharge).find('td.unviewable,th.unviewable')).length > 0) {
        coltarget = $(tableincharge).find('td.colindex,th.unviewable')[index];
    }
    else {
        coltarget = $(tableincharge).find('th')[index];
    }
    var _code = $(coltarget).attr("code");
    if (typeof _code != "undefined" && _code != "") {
        if (!show) {
            $('td[code="' + _code + '"],th[code="' + _code + '"]').hide();
        } else {
            $('td[code="' + _code + '"],th[code="' + _code + '"]').show();
        }
    } else {
        var _realindex = $($(tableincharge).find("th")).index(coltarget);
        //$.each($(tableincharge).find("tr"), function (i, item) {
        if (!show) {
            $(tableincharge).find('tr td:nth-child(' + (_realindex + 1) + ')').hide();
            $($(tableincharge).find("th")[_realindex]).hide();
        } else {
            $(tableincharge).find('tr td:nth-child(' + (_realindex + 1) + ')').show();
            $($(tableincharge).find("th")[_realindex]).show();
        }
        //});
    }
}
$.fn.InitResize = function () {
    $(this).each(function () {
        $(this).mousedown(function (e) {
            curentresizeitem = $(this).parent();
            if ($(curentresizeitem).length == 0)
                return;
            var curpos = $(curentresizeitem).position();
            $.each($(curentresizeitem).parent().parent().children(".fake-tr").children("th,td"), function (i, fcol) {
                if ($(fcol).position().left > curpos.left - 5 && $(fcol).position().left < curpos.left + 5) {
                    relateresizeitem = fcol;
                    resizecolindex = i;
                    return;
                }
            });

            curleft = $(curentresizeitem).position().left;
            var start_x = e.pageX;
            var start_y = e.pageY;

            $(document).mousemove(function (e) {
                var offset_x = e.pageX - start_x;
                var offset_y = e.pageY - start_y;
                if (e.pageX - curleft > 40) {
                    $(curentresizeitem).css("min-width", e.pageX - curleft);
                    $(curentresizeitem).css("max-width", e.pageX - curleft);
                    $(curentresizeitem).css("width", e.pageX - curleft);
                    $(relateresizeitem).children().css("width", e.pageX - curleft);
                }
                var fcindex = $(curentresizeitem).children(".item-resize").attr("tableindex");
                if (typeof fcindex != "undefined") {
                    $($($('table[resizeable="true"]')[fcindex]).find("thead")).html($($("#fakehead" + fcindex).find("thead")).html());
                }
                return false;
            });
            $(document).mouseup(function () {
                $(document).unbind("mousemove");
                $(document).unbind("mouseup");
                if (curentresizeitem == null) {
                    return false;
                }
                var tabletarget = $(curentresizeitem).parent().parent().parent();
                var fcindex = $(curentresizeitem).children(".item-resize").attr("tableindex");
                if (typeof fcindex != "undefined" && fcindex != "") {
                    tabletarget = $('table[resizeable="true"]')[fcindex];
                }

                var _itemwidth = $(curentresizeitem).css("width");
                if (typeof _itemwidth != "undefined")
                    _itemwidth = parseInt(_itemwidth);
                $.each($(tabletarget).children("tbody").children("tr"), function (i, item) {
                    $($(item).children("td")[resizecolindex]).attr("width", (_itemwidth - 1) + "px");
                    $($(item).children("td")[resizecolindex]).css("min-width", _itemwidth - 1);
                    $($(item).children("td")[resizecolindex]).css("max-width", _itemwidth - 1);
                });
                if (typeof fcindex != "undefined" && fcindex != "") {
                    $.each($(tabletarget).find("tr.fake-tr td,tr.fake-tr th"), function (i, item) {
                        var _w = $(item).width();
                        $(item).children().width(_w);
                        $($('#fakehead' + fcindex).find("tr.fake-tr td,tr.fake-tr th")[i]).children().width(_w);
                    });

                    $('#fakehead' + fcindex).width($(tabletarget).width());
                }
                curentresizeitem = null;
                return false;
            });
            return false;
        });
    });
}

$.fn.SelectColumn = function (options) {
    var o = $.extend({
        buttonid: "selectcolumn",
        usegroup: false,
        viewtype: "list", // or category
        showgroupname: false,
        checkalltype: "button",
        cookie: null
    }, options);
    var btn = o.buttonid;
    var usegroup = o.usegroup;
    var viewtype = o.viewtype;
    var checkalltype = o.checkalltype;
    var showgroupname = o.showgroupname;
    var cookiename = o.cookie;
    tableincharge = this;
    $("#" + btn).addClass("select-column");
    var htmlselect = "";
    var unviewcols;
    if ($($(this).find('td.unviewable,th.unviewable')).length > 0) {
        unviewcols = $(this).find('td.unviewable,th.unviewable');
    } else {
        unviewcols = $(this).find("th");
    }
    if ($(unviewcols).length == 0)
        return;

    var groups = new Array();
    var gtext = "";
    var grouphtml = "";
    var catarr = new Array();
    var temp;
    var cookie;
    if (cookiename != null)
        cookie = $.cookie(cookiename);
    $.each(unviewcols, function (i, item) {
        gtext = $(item).attr("groupname");
        if (typeof gtext == "undefined") {
            gtext = "";
        }

        if (typeof $(item).attr("viewstate") != "undefined" && $(item).attr("viewstate") == "hidden") {
            temp = "<li><input groupname='" + gtext + "' type='checkbox'>" + $(item).text() + "</input></li>";
            HideColumn(i, false);
        } else {
            temp = "<li><input groupname='" + gtext + "' type='checkbox' checked='checked'>" + $(item).text() + "</input></li>";
        }

        var inarr = $.inArray(gtext, groups);
        if (inarr < 0) {
            groups.push(gtext);
            catarr.push(temp);
        } else if (viewtype.toLowerCase() == "category") {
            var _v = catarr[inarr] + temp;
            catarr[inarr] = _v;
        }

        if (viewtype.toLowerCase() == "list") {
            htmlselect += temp;
        }
    });

    if (viewtype.toLowerCase() == "list") {
        htmlselect = ("<div class='select-column-items' style=''><ul style='padding:0; margin:0;list-style-type:none; '>" + htmlselect + "</ul></div>");
        if (groups.length > 0 && usegroup) {
            grouphtml = "<div class='group-column'><ul>";
            $.each(groups, function (i, item) {
                grouphtml += "<li groupname='" + item + "'><input type='checkbox'>" + (showgroupname ? item : "Check all") + "</input></li>";
            });
            grouphtml += "</ul></div>";
        }
        var html = "<div id='" + btn + "context' class='header-context'>" + grouphtml + htmlselect + "</div>";
        $("body").append(html);
    } else if (viewtype.toLowerCase() == "category") {
        if (groups.length > 0 && usegroup) {
            var html = "";
            $.each(groups, function (i, item) {
                grouphtml = "<div style='float:left;'>";
                grouphtml += "<div class='group-column'>";
                if (checkalltype.toLowerCase() == 'button') {
                    grouphtml += "<input type='button' groupname='" + item + "' value='Check all'/>";
                } else {
                    grouphtml += "<ul><li groupname='" + item + "'><input type='checkbox' >" + (showgroupname ? item : "Check all") + "</input></li></ul>";
                }
                grouphtml += "</div>";
                temp = "<div class='select-column-items' style=''><ul style='padding:0; margin:0;list-style-type:none; '>" + catarr[i] + "</ul></div>";
                grouphtml = (grouphtml + temp + "</div>");
                html += grouphtml;
            });
            html += "<div style='clear:both'></div>";
            $("body").append("<div id='" + btn + "context' class='header-context'>" + html + "</div>");

            $.each(groups, function (i, item) {
                var _ischecked = $('#' + btn + 'context .select-column-items li input[groupname="' + item + '"]:checked').length;
                var checkboxlength = $('#' + btn + 'context .select-column-items li input[groupname="' + item + '"]').length;
                if (_ischecked == checkboxlength) {
                    if (checkalltype.toLowerCase() == 'button') {
                        $("#" + btn + 'context .group-column input[groupname="' + item + '"]').val("Uncheck all");
                    } else {
                        $("#" + btn + 'context .group-column li[groupname="' + item + '"] input').attr("checked", "checked");
                    }

                }
            });
        }
    }

    $("#" + btn + "context .select-column-items li input").change(function () {
        var colindex = $("#" + btn + "context .select-column-items li").index($(this).parent());
        if ($(this).is(':checked')) {
            HideColumn(colindex, true);
        } else {
            HideColumn(colindex, false);
        }
    });

    $("#" + btn + "context .group-column li input").change(function () {
        var _gtext = $(this).parent().attr("groupname");
        var _ischecked = $(this).is(':checked');
        $.each($('#' + btn + 'context .select-column-items li input[groupname="' + _gtext + '"]'), function (i, item) {
            if (_ischecked) {
                $(item).attr("checked", "checked");
            } else {
                $(item).removeAttr("checked");
            }
            HideColumn($("#" + btn + "context .select-column-items li").index($(item).parent()), $(this).is(':checked'));
        });
    });

    $("#" + btn + 'context .group-column input[type="button"]').click(function () {
        var _gtext = $(this).attr("groupname");
        var _ischecked = $('#' + btn + 'context .select-column-items li input[groupname="' + _gtext + '"]:checked').length;
        var checkboxlength = $('#' + btn + 'context .select-column-items li input[groupname="' + _gtext + '"]').length;
        if (_ischecked != checkboxlength) {
            $(this).val("Uncheck all");
        } else {
            $(this).val("Check all");
        }
        $.each($('#' + btn + 'context .select-column-items input[groupname="' + _gtext + '"]'), function (i, item) {
            if (_ischecked == checkboxlength) {
                $(item).removeAttr("checked");
            } else {
                $(item).attr("checked", "checked");
            }
            HideColumn($("#" + btn + "context .select-column-items input").index($(item)), (_ischecked != checkboxlength));
        });
    });

    $("#" + btn).click(function () {
        var _context = $("#" + btn + "context");
        var _top = $(this).position().top;
        var _left = $(this).position().left;
        var _width = $(_context).width();
        var _height = $(_context).height();
        var maxw = $(document).width();
        var maxh = $(document).height();

        if ((_left + _width) > maxw && (_left - _width) > 0) {
            $(_context).css("left", (_left - _width) + "px");
        } else {
            $(_context).css("left", (_left + 8) + "px");
        }

        if ((_top + _height) > maxh && (_top - _height) > 0) {
            $(_context).css("top", (_top - _height - 10) + "px");
        } else {
            $(_context).css("top", (_top + 10) + "px");
        }
        $(_context).show();
        $(_context).outside('click', this, function (e) {
            $(this).hide();
        });
    });
}